import React, { useEffect, useState } from 'react';
import ImagePreview from './components/ImagePreview';
import Settings from './components/Settings';
import ShortcutDisplay from './components/ShortcutDisplay';
import './styles/App.css';

interface ScreenshotHistory {
  id: string;
  timestamp: Date;
  filename: string;
  dataURL: string;
}



const App: React.FC = () => {
  const [screenshots, setScreenshots] = useState<ScreenshotHistory[]>([]);
  const [isCapturing, setIsCapturing] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [previewImage, setPreviewImage] = useState<ScreenshotHistory | null>(null);

  // 监听截图保存事件
  useEffect(() => {
    const handleScreenshotSaved = (event: any, screenshotInfo: { filename: string; dataURL: string; savedPath: string }) => {
      const newScreenshot: ScreenshotHistory = {
        id: Date.now().toString(),
        timestamp: new Date(),
        filename: screenshotInfo.filename,
        dataURL: screenshotInfo.dataURL
      };
      
      setScreenshots(prev => [newScreenshot, ...prev]);
      console.log('截图已添加到历史记录:', screenshotInfo.filename);
    };

    // 注册事件监听器
    window.electronAPI.on('screenshot-saved', handleScreenshotSaved);

    // 清理函数
    return () => {
      window.electronAPI.removeAllListeners('screenshot-saved');
    };
  }, []);

  const handleCapture = async () => {
    try {
      setIsCapturing(true);
      const dataURLs = await window.electronAPI.captureScreen();
      
      if (dataURLs && dataURLs.length > 0) {
        // 这里会打开截图选择窗口
        console.log('全屏截图数据获取成功');
      }
    } catch (error) {
      console.error('截图失败:', error);
      alert('截图失败，请重试');
    } finally {
      setIsCapturing(false);
    }
  };



  const handleOpenSettings = () => {
    setShowSettings(true);
  };

  const handleCloseSettings = () => {
    setShowSettings(false);
  };

  const handleSave = async (dataURL: string) => {
    try {
      const filename = `screenshot-${Date.now()}.png`;
      const savedPath = await window.electronAPI.saveScreenshot(dataURL, filename);
      
      const newScreenshot: ScreenshotHistory = {
        id: Date.now().toString(),
        timestamp: new Date(),
        filename,
        dataURL
      };
      
      setScreenshots(prev => [newScreenshot, ...prev]);
      alert(`截图已保存到: ${savedPath}`);
    } catch (error) {
      console.error('保存失败:', error);
      alert('保存失败，请重试');
    }
  };

  const handleCopyToClipboard = async (dataURL: string) => {
    try {
      const success = await window.electronAPI.copyToClipboard(dataURL);
      if (success) {
        alert('截图已复制到剪贴板');
      } else {
        alert('复制到剪贴板失败');
      }
    } catch (error) {
      console.error('复制失败:', error);
      alert('复制失败，请重试');
    }
  };

  const deleteScreenshot = (id: string) => {
    setScreenshots(prev => prev.filter(s => s.id !== id));
  };

  // 预览图片
  const previewScreenshot = (screenshot: ScreenshotHistory) => {
    setPreviewImage(screenshot);
  };

  // 关闭预览
  const closePreview = () => {
    setPreviewImage(null);
  };

  // 预览中的操作
  const handlePreviewCopy = async () => {
    if (previewImage) {
      await handleCopyToClipboard(previewImage.dataURL);
      closePreview();
    }
  };

  const handlePreviewSave = async () => {
    if (previewImage) {
      await handleSave(previewImage.dataURL);
    }
  };

  const handlePreviewDelete = () => {
    if (previewImage) {
      deleteScreenshot(previewImage.id);
      closePreview();
    }
  };

  return (
    <div className="app">
      <header className="app-header">
        <div className="header-content">
          <div className="header-text">
            <h1>Cut Pic - 区域截图工具</h1>
            <p>简单易用的桌面区域截图工具</p>
          </div>
          <button 
            className="settings-btn"
            onClick={handleOpenSettings}
            title="设置"
          >
            ⚙️ 设置
          </button>
        </div>
      </header>

      <main className="app-main">
        <div className="capture-section">
          <div className="card">
            <h2>开始截图</h2>
            <p>点击按钮开始区域截图，或使用快捷键进行快速截图</p>
            <div className="capture-controls">
              <button 
                className="btn-primary capture-btn"
                onClick={handleCapture}
                disabled={isCapturing}
              >
                {isCapturing ? '正在准备截图...' : '开始截图'}
              </button>
            </div>
            <ShortcutDisplay />
          </div>
        </div>

        <div className="history-section">
          <div className="card">
            <h2>截图历史</h2>
            {screenshots.length === 0 ? (
              <p className="empty-state">暂无截图记录</p>
            ) : (
              <div className="screenshot-grid">
                {screenshots.map(screenshot => (
                  <div key={screenshot.id} className="screenshot-item">
                    <div className="screenshot-preview">
                      <img 
                        src={screenshot.dataURL} 
                        alt={screenshot.filename}
                        onClick={() => handleSave(screenshot.dataURL)}
                      />
                    </div>
                    <div className="screenshot-info">
                      <span className="filename">{screenshot.filename}</span>
                      <span className="timestamp">
                        {screenshot.timestamp.toLocaleString()}
                      </span>
                      <div className="screenshot-actions">
                        <button 
                          className="btn-primary"
                          onClick={() => previewScreenshot(screenshot)}
                        >
                          🔍 预览
                        </button>
                        <button 
                          className="btn-secondary"
                          onClick={() => handleCopyToClipboard(screenshot.dataURL)}
                        >
                          复制到剪贴板
                        </button>
                        <button 
                          className="btn-secondary"
                          onClick={() => handleSave(screenshot.dataURL)}
                        >
                          重新保存
                        </button>
                        <button 
                          className="btn-secondary delete-btn"
                          onClick={() => deleteScreenshot(screenshot.id)}
                        >
                          删除
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </main>

      <footer className="app-footer">
        <p>使用 Electron + React + TypeScript 构建</p>
      </footer>

      {showSettings && (
        <Settings onClose={handleCloseSettings} />
      )}

      {previewImage && (
        <ImagePreview
          imageUrl={previewImage.dataURL}
          filename={previewImage.filename}
          timestamp={previewImage.timestamp}
          onClose={closePreview}
          onCopy={handlePreviewCopy}
          onSave={handlePreviewSave}
          onDelete={handlePreviewDelete}
        />
      )}
    </div>
  );
};

export default App;